﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Grishko.Tools;
using OutdoorLib.BaseEntity.Face;
using Grishko.DataTier;
using Grishko.UI;
using OutdoorLib.BaseEntity.Dictionary;

public partial class ClientEditor : MasterPage_EditControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MyInit();
        if (!IsPostBack)
                    MyDataBind();
        
        SetAlertForTextBox();
    }

    private void MyInit()
    {
        
        ctlContactFaces1 .DataSource = ContactFacesSource;
        ctlContactFaces1.OnRemoveClick = BntOnRemoveFaceClick_Click;
    }
    private void MyDataBind()
    {
        lvCurator.DataSource = ClientAsList;
        lvAccount .DataSource = ClientAsList;        
        lvCurator.DataSource = ClientAsList;
        lvContactInfo.DataSource = ClientAsList;
        lvCategory.DataSource = ClientAsList;
        DataBind();
    }

    protected void ReadForm()
    {
        Client.Name = txtName.Text;
        Client.Rating = RatingValue.CurrentRating;
        
 
    }

    private bool Save()
    {
        try
        {
            // проверить бизнес правила на вставку/обновление                        
            List<string> CheckResult = AppEnvironment.BusinessRules.CheckUpdate(Client);

            if (0 == CheckResult.Count)
            {
                AppEnvironment.ObjectFactory.SaveObject(Client);
                return true;
            }
            else
            {
                AppEnvironment.Helper.RegistredStartUpAlert(this, CheckResult);
                return false;
            }

        }
        catch
        {
            return false;
        }
              
    }

    protected void btnSaveExit_Click(object sender, EventArgs e)
    {
        ReadForm();

        if(Save())    
            QueryStringTools.RefreshPageWitchReturnUrl();

    }

    protected void btnSaveCommonInfo_Click(object sender, EventArgs e)
    {
        ReadForm();
        if(Save())
            HideAlert();
    }

    #region ListView
    protected void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
    }
    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;

        ListView lv = (ListView)sender;

        switch (lv.ID)
        {
            case "lvCurator":
                LvUpdCmd = UpdateCurator;
                break;
            case "lvCategory":
                LvUpdCmd = UpdateCategoria;
                break;
            case "lvContactInfo":
                LvUpdCmd = UpdateAddress;
                break;
            case "lvAccount":
                LvUpdCmd = UpdateAccount;
                break;        

        }

        switch (e.CommandName)
        {
            case "Edit":
                {
                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;

                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {

                    // обновить поле
                    if (LvUpdCmd((ListViewDataItem)e.Item))
                    {
                        lv.EditIndex = -1;
                        // если бизнес правила в порядке -попытаться неявно сохраниться
                        if (AppEnvironment.BusinessRules.CheckUpdate(Client).Count == 0)
                        {
                            if (Save())
                            {
                                HideAlert();
                                break;
                            }

                        }
                        // Если вышли из блока без сохранения - показать предупреждение  
                        ShowAlert();
                    }
                    break;             
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                    
                }
        }

        MyDataBind();
        SetAlertForTextBox();



    }
    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {

        ListView lv = (ListView)sender;
        TreeDictionaryControl_Rb tv = null;
        TreeDictionaryItem source = null;
        switch (lv.ID)
        {
            case "lvCategory":                 
                source = AppEnvironment.DictionarySource.GetTreeDictionaryItem(TreeDictionaryItem.TreeDictionary_ClientsCategory);
                tv = (TreeDictionaryControl_Rb)lvCategory.EditItem.FindControl("tvCategory");
                tv.TreeDictionaryItemValue = (Client.Ctegoria == null ? source.BuildValue() : Client.Ctegoria);
                tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_ClientsCategory);
                tv.DataBind();
                break;
        }


    }
    protected ListItemCollection EmplSource
    {
        get 
        {
            
            List<EntitySingle> lst = AppEnvironment.Helper.GetObjectCollection("Employeer");
            ListItemCollection result = new ListItemCollection();
            foreach (Employeer item in lst)
            {
                ListItem nl = new ListItem(item.FullName, item.ID);
                result.Add(nl);
            }
            return result;
        }
    }

        

    protected void ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        //// Проверить тип строчки - если это строчка редактирования - зацепить требуемый DS

        //ListView lv = (ListView)sender;
        //switch (lv.ID)
        //{
        //    case "lvStatus":
        //        {
        //            object tv = e.Item.FindControl("tvStatus");
        //            if (null != tv)
        //            {
        //                ((TreeView)tv).DataSource = GetEmployeeSource("chTree_Status", "ctl00_cphHead_hf_tvStatus");
        //                ((TreeView)tv).DataBind();

        //            }
        //            break;
        //        }

        //    case "lvCategoria":
        //        {

        //            object tv = e.Item.FindControl("tvCategoria");
        //            if (null != tv)
        //            {
        //                ((TreeView)tv).DataSource = GetCategoriaSource("chTree_Categoria", "ctl00_cphHead_hf_tvCategoria");
        //                ((TreeView)tv).DataBind();

        //            }
        //            break;
        //        }

        //}

    }
    #endregion

    #region LvUpdate
    Func<ListViewDataItem, bool> LvUpdCmd;
    private bool UpdateCurator(ListViewDataItem item)
    {
        DropDownList cmb = (DropDownList)lvCurator.EditItem.FindControl("cmbEmpl");
        if (!string.IsNullOrEmpty(cmb.SelectedValue))
            Client.Curator = (Employeer)AppEnvironment.Helper.GetObject(cmb.SelectedValue);
        
        return true;
    }

    private bool UpdateCategoria(ListViewDataItem item)
    {
        TreeDictionaryControl_Rb tv;
        tv = (TreeDictionaryControl_Rb)lvCategory.EditItem.FindControl("tvCategory");
        tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_ClientsCategory);
        Client.Ctegoria = tv.TreeDictionaryItemValue;
        return true;
    }


    private bool UpdateAddress(ListViewDataItem item)
    {
        TextBox box=(TextBox)item.FindControl("txtPhones");
        Client.Phones = box.Text;
        box = (TextBox)item.FindControl("txtAdress");
        Client.Adress = box.Text;
        box = (TextBox)item.FindControl("txtMail");
        Client.Email = box.Text;
        box = (TextBox)item.FindControl("txtUrl");
        Client.URL = box.Text;        
        return true;
    }

    private bool UpdateAccount(ListViewDataItem item)
    {
        TextBox box = (TextBox)item.FindControl("txtINN");
        Client.INN   = box.Text;
        box = (TextBox)item.FindControl("txtOKPO");
        Client.OKPO = box.Text;
        box = (TextBox)item.FindControl("txtAccount");
        Client.Account  = box.Text;        
        return true;
    }

    #endregion

    #region Source
    private Client _Client = null;
    protected Client Client
    {
        get
        {
            if (null != _Client)
            {
                AppEnvironment.BusinessRules.SetDefaultValue(_Client, null);
                return _Client;
            }

            if (GlobalConstants.IsNewRecord(CurrentID))
                _Client = (Client)AppEnvironment.ObjectFactory.GetNewObject(CurrentTagName, GlobalConstants.GetNewID(CurrentID));
            else
                _Client = (Client)AppEnvironment.ObjectFactory.GetObject(CurrentID, CurrentTagName);

            return _Client ;
        }

    }

    protected List<Client> ClientAsList
    {
        get 
        {
                List<Client> r = new List<Client>();
                r.Add(Client);
                return r;
        }
    }
   
    protected EntityList ContactFacesSource()
    {
        return Client.ContactFaces;
    }


    #endregion

    protected void BntAddFace_Click(object sender, EventArgs e)
    {
        ContactFace _ContactFace = (ContactFace)AppEnvironment.ObjectFactory.GetNewObject("ContactFace", Guid.NewGuid ().ToString () );
        AppEnvironment.ObjectFactory.SaveObject(_ContactFace);
        Client.ContactFaces.Add(_ContactFace);
        if(Save ())
            MyDataBind();
    }
    protected bool BntOnRemoveFaceClick_Click(ContactFace  Face) 
    {   
        //удаляем ссылку из списка 
        Client.ContactFaces.Remove(Face.ID);
        if (Save())
        {
            // удаляем сам объект
            Face.DestroyMySelf();
            AppEnvironment.ObjectFactory.SaveObject(Face);
            MyDataBind();
            return true;
        }

        return false;

    }
}
